package com.demo.controller;

import com.demo.common.Result;
import com.demo.pojo.dto.ScheduleListDTO;
import com.demo.pojo.entity.Student;
import com.demo.service.StudentUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 学生用户控制器
 */
@RestController
@RequestMapping("/student-user")
@CrossOrigin
public class StudentUserController {
    
    @Autowired
    private StudentUserService studentUserService;
    
    /**
     * 学生登录
     */
    @PostMapping("/login")
    public Result<Student> studentLogin(@RequestParam Long stuNo, @RequestParam String password) {
        try {
            Student student = studentUserService.studentLogin(stuNo, password);
            if (student != null) {
                return Result.success(student);
            } else {
                return Result.error("登录失败，学号或密码错误");
            }
        } catch (Exception e) {
            return Result.error("登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取学生个人信息
     */
    @GetMapping("/info/{studentId}")
    public Result<Student> getStudentInfo(@PathVariable Long studentId) {
        try {
            Student student = studentUserService.getStudentInfo(studentId);
            return Result.success(student);
        } catch (Exception e) {
            return Result.error("获取学生信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新学生个人信息
     */
    @PutMapping("/update")
    public Result<String> updateStudentInfo(@RequestBody Student student) {
        try {
            boolean success = studentUserService.updateStudentInfo(student);
            if (success) {
                return Result.success("更新学生信息成功");
            } else {
                return Result.error("更新学生信息失败");
            }
        } catch (Exception e) {
            return Result.error("更新学生信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取学生课表
     */
    @GetMapping("/schedule/{studentId}/{semester}")
    public Result<List<ScheduleListDTO>> getStudentSchedule(@PathVariable Long studentId,
                                                           @PathVariable String semester) {
        try {
            List<ScheduleListDTO> schedules = studentUserService.getStudentSchedule(studentId, semester);
            return Result.success(schedules);
        } catch (Exception e) {
            return Result.error("获取学生课表失败：" + e.getMessage());
        }
    }

    /**
     * 获取学生课表（学期可选，后端兜底 advanced -> 2025-1）
     */
    @GetMapping("/schedule/{studentId}")
    public Result<List<ScheduleListDTO>> getStudentScheduleFallback(@PathVariable Long studentId,
                                                                   @RequestParam(value = "semester", required = false) String semester) {
        try {
            String used = (semester == null || semester.isBlank()) ? "advanced" : semester;
            List<ScheduleListDTO> schedules = studentUserService.getStudentSchedule(studentId, used);
            if ((schedules == null || schedules.isEmpty()) && !"2025-1".equals(used)) {
                schedules = studentUserService.getStudentSchedule(studentId, "2025-1");
            }
            return Result.success(schedules);
        } catch (Exception e) {
            return Result.error("获取学生课表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取学生本周课表
     */
    @GetMapping("/schedule/week/{studentId}/{semester}/{weekNo}")
    public Result<List<ScheduleListDTO>> getStudentWeekSchedule(@PathVariable Long studentId, 
                                                              @PathVariable String semester, 
                                                              @PathVariable Integer weekNo) {
        try {
            List<ScheduleListDTO> schedules = studentUserService.getStudentWeekSchedule(studentId, semester, weekNo);
            return Result.success(schedules);
        } catch (Exception e) {
            return Result.error("获取学生本周课表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取学生今日课表
     */
    @GetMapping("/schedule/today/{studentId}/{semester}/{weekNo}/{dayOfWeek}")
    public Result<List<ScheduleListDTO>> getStudentTodaySchedule(@PathVariable Long studentId, 
                                                               @PathVariable String semester, 
                                                               @PathVariable Integer weekNo, 
                                                               @PathVariable Integer dayOfWeek) {
        try {
            List<ScheduleListDTO> schedules = studentUserService.getStudentTodaySchedule(studentId, semester, weekNo, dayOfWeek);
            return Result.success(schedules);
        } catch (Exception e) {
            return Result.error("获取学生今日课表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取可选课程列表
     */
    @GetMapping("/courses/available/{studentId}/{semester}")
    public Result<List<Map<String, Object>>> getAvailableCourses(@PathVariable Long studentId, 
                                                               @PathVariable String semester) {
        try {
            List<Map<String, Object>> courses = studentUserService.getAvailableCourses(studentId, semester);
            return Result.success(courses);
        } catch (Exception e) {
            return Result.error("获取可选课程列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 学生选课
     */
    @PostMapping("/course/select")
    public Result<String> selectCourse(@RequestParam Long studentId, @RequestParam Long courseId) {
        try {
            boolean success = studentUserService.selectCourse(studentId, courseId);
            if (success) {
                return Result.success("选课成功");
            } else {
                return Result.error("选课失败，可能已选过该课程");
            }
        } catch (Exception e) {
            return Result.error("选课失败：" + e.getMessage());
        }
    }
    
    /**
     * 学生退课
     */
    @PostMapping("/course/drop")
    public Result<String> dropCourse(@RequestParam Long studentId, @RequestParam Long courseId) {
        try {
            boolean success = studentUserService.dropCourse(studentId, courseId);
            if (success) {
                return Result.success("退课成功");
            } else {
                return Result.error("退课失败，可能未选该课程");
            }
        } catch (Exception e) {
            return Result.error("退课失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取学生已选课程
     */
    @GetMapping("/courses/selected/{studentId}/{semester}")
    public Result<List<Map<String, Object>>> getSelectedCourses(@PathVariable Long studentId, 
                                                              @PathVariable String semester) {
        try {
            List<Map<String, Object>> courses = studentUserService.getSelectedCourses(studentId, semester);
            return Result.success(courses);
        } catch (Exception e) {
            return Result.error("获取已选课程失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取学生成绩
     */
    @GetMapping("/grades/{studentId}/{semester}")
    public Result<List<Map<String, Object>>> getStudentGrades(@PathVariable Long studentId, 
                                                            @PathVariable String semester) {
        try {
            List<Map<String, Object>> grades = studentUserService.getStudentGrades(studentId, semester);
            return Result.success(grades);
        } catch (Exception e) {
            return Result.error("获取学生成绩失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取学生学分统计
     */
    @GetMapping("/credits/{studentId}")
    public Result<Map<String, Object>> getStudentCreditStats(@PathVariable Long studentId) {
        try {
            Map<String, Object> stats = studentUserService.getStudentCreditStats(studentId);
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取学生学分统计失败：" + e.getMessage());
        }
    }
}
